from django.contrib import admin
from django.utils.html import format_html
from paw.models import User, Product, Category

from django.contrib.auth.hashers import make_password

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('phone', 'nickname', 'is_active', 'date_joined')
    list_filter = ('is_active', 'is_staff', 'is_superuser')
    search_fields = ('phone', 'nickname')
    ordering = ('-date_joined',)
    fieldsets = (
        (None, {
            'fields': ('phone', 'password')
        }),
        ('个人信息', {
            'fields': ('nickname', 'id_card')
        }),
        ('权限', {
            'fields': ('is_active', 'is_staff', 'is_superuser')
        }),
        ('重要日期', {
            'fields': ('date_joined',)
        }),
    )
    readonly_fields = ('date_joined',)

    def save_model(self, request, obj, form, change):
        # 如果是新增用户或密码被修改，则进行加密
        if not change or 'password' in form.changed_data:
            obj.password = make_password(obj.password)
        super().save_model(request, obj, form, change)

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('name',)
    ordering = ('name',)
    fieldsets = (
        (None, {
            'fields': ('name', 'parent')
        }),
        ('时间信息', {
            'fields': ('created_at',)
        }),
    )
    readonly_fields = ('created_at',)

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ('title', 'category', 'publisher', 'is_displayed', 'price', 'created_at', 'image_tag')
    list_filter = ('category', 'created_at')
    search_fields = ('title', 'description', 'publisher__nickname')
    ordering = ('-created_at',)
    fieldsets = (
        (None, {
            'fields': ('title', 'category', 'publisher', 'is_displayed', 'price', 'description', 'image')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        }),
    )

    def image_tag(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="50" height="50" />', obj.image.url)
        return '无图片'
    image_tag.short_description = '商品图片'
    readonly_fields = ('created_at', 'updated_at')
